//
//  ReloadDataViewController.m
//  IpadR
//
//  Created by edianzu on 2017/5/24.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "ReloadDataViewController.h"
#import "ChooseSchoolViewController.h"
@interface ReloadDataViewController ()
@property (nonatomic,strong)SchoolModel * schoolModel;
@property (nonatomic,copy)NSString * AllStr;
@end

@implementation ReloadDataViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [HexColor colorWithHexString:Green_One];
        [self creatBtn];
}

-(void)creatBtn{
    _reloadDataBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _reloadDataBtn.backgroundColor = UIColorFromRGB(223, 242, 241);
    [_reloadDataBtn setTitle:@"更新数据" forState:UIControlStateNormal];
    [_reloadDataBtn addTarget:self action:@selector(reloadData) forControlEvents:UIControlEventTouchUpInside];
    _reloadDataBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19*AutoScaleHorizontal];
    [_reloadDataBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_reloadDataBtn];
    [_reloadDataBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(200*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(250*AutoScaleHorizontal, 50*AutoScaleVertical));
    }];
    
    _chooseSchoolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _chooseSchoolBtn.backgroundColor = [HexColor colorWithHexString:Orange_One];
    [_chooseSchoolBtn setTitle:@"选择幼儿园" forState:UIControlStateNormal];
    [_chooseSchoolBtn addTarget:self action:@selector(chooseSchool) forControlEvents:UIControlEventTouchUpInside];
    _chooseSchoolBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19*AutoScaleHorizontal];
    [_chooseSchoolBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:_chooseSchoolBtn];
    [_chooseSchoolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).with.offset(-200*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(250*AutoScaleHorizontal, 50*AutoScaleVertical));
    }];
    
    _chooseSchoolIMG = [[UIImageView alloc]init];
    _chooseSchoolIMG.image = [UIImage imageNamed:@"chooseSchool"];
    [_chooseSchoolBtn addSubview:_chooseSchoolIMG];
    [_chooseSchoolIMG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(_chooseSchoolBtn.mas_centerY);
        make.right.mas_equalTo(_chooseSchoolBtn.mas_right).with.offset(-50*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(10*AutoScaleHorizontal, 10*AutoScaleVertical));
    }];
}

#pragma mark 更新数据
-(void)reloadData{
    
    //判断是否有数据需要上传，如果有，则不能更新
    NSString* str = [[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"];//获取全部数据
    if (str !=nil) {
        
    
    
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary * readyToLoadArr = [[NSMutableDictionary alloc]init];
    readyToLoadArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    ///////////////
    NSInteger readyToLoadCount = 0;
    for (NSMutableDictionary * dic in [readyToLoadArr objectForKey:@"Children"]) {
        //        [dic setValue:@"1" forKey:@"ValueChanged"];//如果改变了孩子，给本地数据加字段以便上传
        if ([dic objectForKey:@"ValueChanged"] != nil) {
            readyToLoadCount +=1;
        }
    }
    if (readyToLoadCount != 0) {
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"检测到有未上传的测量数据，请选择已体测但未上传数据的园所，先上传数据" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
    }else{

    
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
    NSLog(@"更新开始");
    self.schoolArray = [[NSMutableArray alloc]init];
    self.classArray = [[NSMutableArray alloc]init];
    self.childArray = [[NSMutableArray alloc]init];
    //菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    //    _HUD.mode = MBProgressHUDModeIndeterminate;
    //     _HUD.opacity = 1;
    self.HUD.color = [UIColor whiteColor];
    self.HUD.dimBackground = YES;
    //设置菊花颜色  只能设置菊花的颜色
    self.HUD.activityIndicatorColor = [UIColor redColor];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES];
    NSString * urls = @"/physicalTest/inputs";
    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSDictionary *parama = @{@"AgencyId":[user objectForKey:@"AgencyId"]};
    [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
        NSLog(@"更新成功");
        [self showMessage:@"更新成功"];
        [self.HUD removeFromSuperview];
        self.HUD = nil;
        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//         NSArray * arr = [dict objectForKey:@"Children"];
//        for (NSDictionary* dic in arr) {
//            NSLog(@"%@,,",[dic objectForKey:@"SitReach"]);
//        }
        for (NSMutableDictionary * dic in  [dict objectForKey:@"Children"]) {
            if ([[dic objectForKey:@"SitReach"] isEqual:@-111]) {
                [dic removeObjectForKey:@"SitReach"];
                
            }
        }
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

        [user removeObjectForKey:@"AllData"];
        [user setObject:self.AllStr forKey:@"AllData"];
        [user synchronize];
        
    } failure:^(NSError *error) {
        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"更新数据失败，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
        NSError * err = error;
        NSLog(@"更新因为这个失败了%@",err.description);
        [self.HUD removeFromSuperview];
        self.HUD = nil;
    }];
    NSLog(@"更新结束");
    }
}
    }else{//如果为第一次登录还没有ALLDATA   直接更新
        NSLog(@"更新开始");
        self.schoolArray = [[NSMutableArray alloc]init];
        self.classArray = [[NSMutableArray alloc]init];
        self.childArray = [[NSMutableArray alloc]init];
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    _HUD.mode = MBProgressHUDModeIndeterminate;
        //     _HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/physicalTest/inputs";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSDictionary *parama = @{@"AgencyId":[user objectForKey:@"AgencyId"]};
        [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"更新成功");
            [self showMessage:@"更新成功"];
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            //         NSArray * arr = [dict objectForKey:@"Children"];
            //        for (NSDictionary* dic in arr) {
            //            NSLog(@"%@,,",[dic objectForKey:@"SitReach"]);
            //        }
            for (NSMutableDictionary * dic in  [dict objectForKey:@"Children"]) {
                if ([[dic objectForKey:@"SitReach"] isEqual:@-111]) {
                    [dic removeObjectForKey:@"SitReach"];
                    
                }
            }
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            [user removeObjectForKey:@"AllData"];
            [user setObject:self.AllStr forKey:@"AllData"];
            [user synchronize];
            
        } failure:^(NSError *error) {
            UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"更新数据失败，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alc addAction:act];
            [self presentViewController:alc animated:YES completion:nil];
            NSError * err = error;
            NSLog(@"更新因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];

    }
}



#pragma mark 选择幼儿园
-(void)chooseSchool{
    NSLog(@"开始选择");
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"] == nil) {
        [self showMessage:@"请先更新数据"];
    }else{
        ChooseSchoolViewController * cvc = [[ChooseSchoolViewController alloc]init];
        UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:cvc];
        navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
        navi.navigationBar.translucent = NO;
        [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
        [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

        [self.navigationController presentViewController:navi animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
